package com.itheima.consumer.controller;

import com.itheima.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..." + id);
        //远程调用Goods服务中的findOne接口
        /*
            使用RestTemplate
            1. 定义Bean  restTemplate
            2. 注入Bean
            3. 调用方法
        */
        /*String url = "http://localhost:8000/goods/findOne/" + id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);*/
        //从eureka 服务列表中获取客户端服务列表，参数表示的是服务id
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER");
        ServiceInstance serviceInstance = instances.get(0);
        int port = serviceInstance.getPort();
        String host = serviceInstance.getHost();
        String instanceId = serviceInstance.getInstanceId();
        System.out.println("port=|"+port+"| host=|"+host+"|  instanceId=|"+instanceId);

        String url="http://"+host+":"+port+"/goods/findOne/"+id;
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;
    }

}
